package com.har.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.har.common.Contans;
import com.har.config.HtConfig;
import com.har.service.HtService;
import com.har.util.MD5Util;
import com.har.utils.date.DateUtil;
import com.har.utils.http.HttpUtil;
import com.har.utils.string.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import static com.har.util.MD5Util.MD5Encode;

/**
 * @author macwy
 * @Title:har-finance
 * @Package com.har.service.impl
 * @Description 华泰保险相关接口
 * @date 2018/7/27 14:01
 * @Version 1.0
 */
@Slf4j
@Service
public class HtServiceImpl  implements HtService {


    @Autowired
    private HtConfig htConfig;


    @Override
    public String orderPay(JSONObject dataJson) {

        dataJson.put("channelCode",htConfig.getChannelCode());
        dataJson.put("sign",orderPaySign(dataJson));


        String payUrl = htConfig.getPrefixUrl()+ Contans.HT__ORDER_PAYCHOOSE;

        try {
          String payResult =  HttpUtil.post(payUrl,dataJson.toJSONString());

            log.info("ht pay result >>> {}",payResult);

            return  payResult;
        } catch (Exception e) {
            log.error("ht pay error");
            e.printStackTrace();
        }


        return null;
    }



    private  String orderPaySign(JSONObject dataJson){
        //Sign=MD5(渠道编码+金额+订单号+交易时间+KEY)，括号中按顺序相加各字段value值

        StringBuffer sb  = new StringBuffer();
        //渠道编号
        String channelCode = htConfig.getChannelCode();
        sb.append("channelCode="+channelCode+"|");

        //支付金额
        String money = dataJson.getString("money");
        sb.append("money="+money+"|");
        //订单号
        String orderNo = dataJson.getString("orderNo");
        sb.append("orderNo="+orderNo+"|");
        //交易时间
        String tradeTime = dataJson.getString("tradeTime");
        sb.append("tradeTime="+tradeTime+"|");
        //key
        String md5Key= htConfig.getMd5Key();

        sb.append("md5Key="+md5Key);

        log.info("ht pay sign >>> {}",sb.toString());

        String sign = channelCode+money+orderNo+tradeTime+md5Key;

        log.info("ht pay sign before >>> {}",sign);

        sign = MD5Encode(sign,"UTF-8");

        log.info("ht pay sign after >>> {}",sign);

        return  sign;
    }

    @Override
    public String orderQuery(JSONObject dataJson) {

        //Sign=MD5(渠道编码+订单号+KEY), 括号中按顺序相加各字段value值

        dataJson.put("channelCode",htConfig.getChannelCode());

        String source = htConfig.getChannelCode()+dataJson.getString("orderNo")+htConfig.getMd5Key();

        String sign = MD5Encode(source,"UTF-8");

        dataJson.put("sign",sign);


        String orderQueryUrl = htConfig.getPrefixUrl()+Contans.HT_ORDER_QUERY;

        try {
            String result =  HttpUtil.post(orderQueryUrl,dataJson.toJSONString());

            log.info("ht order query result >> {}",result);
            return  result;
        } catch (Exception e) {
            log.error("ht order query error ");
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public String generateOrderNo() {


        String time = DateUtil.convertDateToStr(new Date(),DateUtil.FORMATE_YYYYMMDDHHMMSS);

        String randomNumber = RandomUtils.generateNumberString(8);

        String orderNo =  htConfig.getChannelCode()+time+randomNumber;


        return orderNo;
    }



    @Override
    public JSONObject payCallBack(HttpServletRequest request) throws Exception {

        JSONObject respJson = new JSONObject();

        //解析请求参数
        Map<String,String[]> map= request.getParameterMap();

        Iterator entries = map.keySet().iterator();

        while (entries .hasNext()) {

            Object key = entries.next();

            String[] val = map.get(key);

            respJson.put(key.toString(),val[0]);

        }
        log.info("ht callBack params >>> {}",respJson.toJSONString());

        //Ht签名
        String sign = respJson.getString("sign");

        //Sign=MD5(渠道编码+订单号+第三方类型+交易流水号+KEY)，括号中按顺序相加各字段value值Sign需要转换成大写

        //验签
        String source = htConfig.getChannelCode()+respJson.getString("orderNo")+respJson.getString("transactionNo")+htConfig.getMd5Key();

        String localSign = MD5Util.MD5Encode(source,"UTF-8");

        if(localSign.equals(sign)){

            respJson.remove("sign");

            return  respJson;
        }

        throw new  Exception ("验签失败");
    }

    @Override
    public String policyHt(JSONObject dataJson) {

        // 签名加密
        String signature = com.har.util.MD5Util.MD5Encode(dataJson.toJSONString()
                + Contans.ENCRYPT_VAL, "utf-8");

        log.info("ht policy signa  >>> {}",signature);

        //投保url
        String policyUrl = htConfig.getPolicyUrl()+ Contans.HT_POLICY;

        log.info("ht policy url  >>> {}",policyUrl);

        try {
            //url参数为投保测试url
            String policyResult =  HttpUtil.post(policyUrl,"json="+dataJson.toJSONString()
                    +"&channelCode="+Contans.CHANNELCODE+"&signature="+signature);

            log.info("ht policy result >>> {}",policyResult);

            return  policyResult;

        } catch (Exception e) {

            log.error("ht policy error");

            e.printStackTrace();
        }

        return null;
    }

}
